package com.platform.config;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Set;

/**
 * Description: freemarker模板定制
 *
 * @author YangLong [410357434@163.com]
 * @version V1.0
 * @date 2020/8/25
 */
@Component
public class FreemarkerConfig {
    @Autowired
    private FreeMarkerViewResolver freeMarkerViewResolver;
    @Value("#{${freeemarker.static}}")
    private HashMap<String,String> staticAttributes;

    /**
     * 配置freemarker模板，设置变量
     *
     * @throws TemplateException 异常
     */
    @PostConstruct
    public void configFreemarker() throws TemplateException{
        FreemarkerStaticModels models=FreemarkerStaticModels.getInstance();
        models.setStaticModels(staticAttributes);
        freeMarkerViewResolver.setAttributesMap(models);
    }

    public static class FreemarkerStaticModels extends HashMap<String, Object> {

        private static final long serialVersionUID = -127L;

        private static FreemarkerStaticModels FREEMARKER_STATIC_MODELS;

        private HashMap<String,String> staticModels;

        private FreemarkerStaticModels() {

        }

        public static FreemarkerStaticModels getInstance() {
            if (FREEMARKER_STATIC_MODELS == null) {
                FREEMARKER_STATIC_MODELS = new FreemarkerStaticModels();
            }
            return FREEMARKER_STATIC_MODELS;
        }

        public HashMap<String, String> getStaticModels() {
            return staticModels;
        }

        public void setStaticModels(HashMap<String,String> staticModels) throws TemplateException {
            if (this.staticModels == null && staticModels != null) {
                this.staticModels = staticModels;
                Set<String> keys = this.staticModels.keySet();
                BeansWrapperBuilder builder=new BeansWrapperBuilder(freemarker.template.Configuration.VERSION_2_3_30);
                builder.setUseModelCache(true);
                builder.setExposeFields(true);
                BeansWrapper wrapper = builder.build();
                TemplateHashModel hashModel = wrapper.getStaticModels();
                for (String key : keys) {
                    FREEMARKER_STATIC_MODELS.put(key, hashModel.get(this.staticModels.get(key)));
                }
            }
        }
    }
}
